#include "clent.h"

using namespace std;

clent::clent(unsigned short p,std::string i):port(p),ip(inet_addr(i.c_str())){
    cout<<"输入你的姓名\n";
    cin>>name;
    cout<<i<<"  port:"<<port<<endl;
}

void clent::start()
{
    cout<<"ip:"<<ip<<"  port:"<<port<<endl;
    
    sock=socket(PF_INET,SOCK_STREAM,0);
    if(sock==-1) error("socket");

    struct sockaddr_in cln_adr;

    bzero(&cln_adr,sizeof(cln_adr));
    cln_adr.sin_port=htons(port);
    cln_adr.sin_family=AF_INET;
    cln_adr.sin_addr.s_addr=ip;

    if((connect(sock,(sockaddr*)&cln_adr,sizeof(cln_adr))==-1))
    error("connect");

    cout<<"开始聊天，发送你的消息：\n";
  thread tsend(&clent::send_msg,this);
  thread trecv(&clent::recv_msg,this);//实现读写分离
    tsend.join();
    trecv.join();
}

void clent::send_msg()
{
    string msg;
    while(1){
      getline(cin,msg);
      if(msg=="q") return;
        msg=(name+": ")+msg;
        char m[BUF_SIZE];
        sprintf(m,"%s",msg.c_str());
        send(sock,m,strlen(m),0);
    }
   
}

void clent::recv_msg(){
    char msg[BUF_SIZE];
    int len=0;
    while(len=recv(sock,msg,BUF_SIZE-1,0)){
    if(len<=0) return;
    msg[len]=0;
    cout<<msg<<endl;}
    cout<<"线程结束"<<endl;
}

int main(){
    clent c(9900);
    c.start();
}
